importScripts('/node_modules/spark-md5/spark-md5.min.js');

self.onmessage = function (e) {
  const file = e.data;
  const chunkSize = 4 * 1024 * 1024;
  const chunks = Math.ceil(file.size / chunkSize);
  let currentChunk = 0;
  const spark = new SparkMD5.ArrayBuffer();
  const fileReader = new FileReader();

  fileReader.onload = function (e) {
    spark.append(e.target.result);
    currentChunk++;

    if (currentChunk < chunks) {
      loadNext();
    } else {
      const md5 = spark.end();
      self.postMessage(md5);
    }
  };

  fileReader.onerror = function (error) {
    self.postMessage(null);
  };

  function loadNext() {
    const start = currentChunk * chunkSize;
    const end = start + chunkSize >= file.size ? file.size : start + chunkSize;
    fileReader.readAsArrayBuffer(file.slice(start, end));
  }

  loadNext();
};